<template>
  <div class="refund-application">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>退款申请</h2>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-header">
        <i class="filter-icon">📊</i>
        <span>筛选</span>
      </div>
      <div class="filter-content">
        <div class="filter-item">
          <label>服务编号：</label>
          <input 
            type="text" 
            v-model="filter.patientInfo" 
            placeholder="请输入服务编号"
            class="filter-input"
          />
        </div>
        <div class="filter-item">
          <label>申请时间：</label>
          <input 
            type="datetime-local" 
            v-model="filter.applyStartTime" 
            class="filter-input"
          />
          <span class="date-separator">至</span>
          <input 
            type="datetime-local" 
            v-model="filter.applyEndTime" 
            class="filter-input"
          />
        </div>
        <button @click="applyFilter" class="filter-button">筛选</button>
      </div>
    </div>
    
    <!-- 数据列表区域 -->
    <div class="data-list-section">
      <div class="data-list-header">
        <i class="data-icon">📋</i>
        <span>数据列表</span>
      </div>
      
      <!-- 状态切换按钮 -->
      <div class="status-tabs">
        <button 
          v-for="tab in statusTabs" 
          :key="tab.key ?? 'all'"
          @click="switchStatus(tab.key)"
          :class="['status-tab', { active: currentStatus === tab.key }]"
        >
          {{ tab.label }}
        </button>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <!-- 数据表格 -->
      <div v-else class="data-table">
        <div class="table-header">
          <span>服务编号</span>
          <span>申请时间</span>
          <span>用户</span>
          <span>退款金额</span>
          <span>来源</span>
          <span>状态</span>
          <span>处理时间</span>
          <span>操作</span>
        </div>
        <div v-if="dataList.length === 0" class="empty-data">
          <p>暂无数据</p>
        </div>
        <div class="table-row" v-for="item in dataList" :key="item.id">
          <span>{{ item.applicationNo || '-' }}</span>
          <span>{{ formatDateTime(item.applyTime) }}</span>
          <span>{{ item.userPhone || '-' }}</span>
          <span>¥{{ item.amount || 0 }}</span>
          <span>{{ item.source || '-' }}</span>
          <span :class="['status', getStatusClass(item.status)]">{{ item.statusText || '未知' }}</span>
          <span>{{ item.processTime ? formatDateTime(item.processTime) : '-' }}</span>
          <span class="action" @click="viewDetail(item)">查看</span>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <span class="pagination-info">共{{ pagination.totalPages }}页/{{ pagination.totalCount }}条数据</span>
        <div class="pagination-controls">
          <button 
            @click="changePage(pagination.currentPage - 1)" 
            :disabled="pagination.currentPage <= 1"
            class="page-btn"
          >
            &lt;
          </button>
          <button 
            v-for="page in visiblePages" 
            :key="page"
            @click="changePage(page)"
            :class="['page-btn', { active: pagination.currentPage === page }]"
          >
            {{ page }}
          </button>
          <button 
            @click="changePage(pagination.currentPage + 1)" 
            :disabled="pagination.currentPage >= pagination.totalPages"
            class="page-btn"
          >
            &gt;
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onActivated, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../utils/request';

const router = useRouter();
const route = useRoute();

// 筛选条件
const filter = reactive({
  patientInfo: '',
  applyStartTime: '',
  applyEndTime: ''
});

// 状态相关
const currentStatus = ref<number | null>(null);
const statusTabs = [
  { key: null as number | null, label: '全部' },
  { key: 0, label: '待处理' },
  { key: 1, label: '已处理' },
  { key: 2, label: '已拒绝' }
];

// 数据相关
const dataList = ref<any[]>([]);
const loading = ref(false);

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0
});

// 计算属性
const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, pagination.currentPage - 2);
  const end = Math.min(pagination.totalPages, pagination.currentPage + 2);
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: any = {};

    // 分页参数
    params.pageIndex = pagination.currentPage;
    params.pageSize = pagination.pageSize;

    // 患者信息筛选
    if (filter.patientInfo && filter.patientInfo.trim()) {
      params.patientInfo = filter.patientInfo.trim();
    }

    // 状态筛选
    if (currentStatus.value !== null) {
      params.status = currentStatus.value;
    }

    // 时间筛选
    if (filter.applyStartTime) {
      params.applyStartTime = new Date(filter.applyStartTime).toISOString();
    }

    if (filter.applyEndTime) {
      params.applyEndTime = new Date(filter.applyEndTime).toISOString();
    }

    console.log('发送API请求，参数:', params);

    const response = await api.refundApplication.getPagedList(params);
    
    console.log('API响应:', response);
    
    if (response && response.data) {
      dataList.value = response.data.items || [];
      pagination.totalCount = response.data.totalCount || 0;
      pagination.totalPages = response.data.totalPages || 0;
      pagination.currentPage = response.data.currentPage || 1;
      
      console.log('数据加载成功:', {
        items: dataList.value.length,
        totalCount: pagination.totalCount,
        totalPages: pagination.totalPages,
        currentPage: pagination.currentPage
      });
    } else {
      console.error('获取数据失败，响应格式不正确');
      dataList.value = [];
    }
  } catch (error) {
    console.error('请求失败:', error);
    dataList.value = [];
  } finally {
    loading.value = false;
  }
};

const applyFilter = () => {
  pagination.currentPage = 1;
  loadData();
};

const switchStatus = (status: number | null) => {
  currentStatus.value = status;
  pagination.currentPage = 1;
  loadData();
};

const formatDateTime = (dateTime: string | null) => {
  if (!dateTime) return '-';
  try {
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return dateTime;
  }
};

const getStatusClass = (status: number | null) => {
  switch (status) {
    case 0: return 'pending';
    case 1: return 'processed';
    case 2: return 'rejected';
    default: return 'pending';
  }
};

const viewDetail = (item: any) => {
  console.log('查看详情:', item);
  // 根据状态跳转到不同页面
  switch (item.status) {
    case 0:
      router.push(`/refund-detail-pending/${item.id}`);
      break;
    case 1:
      router.push(`/refund-detail-processed/${item.id}`);
      break;
    case 2:
      router.push(`/refund-detail-rejected/${item.id}`);
      break;
    default:
      router.push(`/refund-detail-pending/${item.id}`);
  }
};

const changePage = (page: number) => {
  if (page >= 1 && page <= pagination.totalPages) {
    pagination.currentPage = page;
    loadData();
  }
};

// 监听路由参数变化，当有refresh参数时重新加载数据
watch(() => route.query.refresh, (newVal) => {
  if (newVal === 'true') {
    loadData();
    // 清除refresh参数
    router.replace({ query: {} });
  }
});

// 生命周期
onMounted(() => {
  loadData();
});

// 当页面重新激活时（从其他页面返回）重新加载数据
onActivated(() => {
  loadData();
});
</script>

<style scoped>
.refund-application {
  padding: 60px 80px 60px 120px;
  min-height: 100vh;
  background-color: white;
}

.page-title h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.filter-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.filter-header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.filter-icon {
  font-size: 16px;
}

.filter-content {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.filter-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.date-separator {
  color: #666;
  font-size: 14px;
}

.filter-button {
  padding: 8px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.3s ease;
}

.filter-button:hover {
  background-color: #40a9ff;
}

.data-list-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.data-list-header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.data-icon {
  font-size: 16px;
}

.status-tabs {
  padding: 20px 20px 0 20px;
  display: flex;
  gap: 10px;
  border-bottom: 1px solid #e9ecef;
}

.status-tab {
  padding: 10px 20px;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s ease;
}

.status-tab:hover {
  color: #1890ff;
}

.status-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: 500;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-data {
  padding: 60px 20px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.data-table {
  width: 100%;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  gap: 15px;
  padding: 15px 20px;
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e9ecef;
}

.empty-data {
  padding: 60px 20px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  gap: 15px;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.table-row:hover {
  background-color: #f8f9fa;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
}

.status.pending {
  background-color: #fff3cd;
  color: #856404;
}

.status.processed {
  background-color: #d4edda;
  color: #155724;
}

.status.rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.action {
  color: #1890ff;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.3s ease;
}

.action:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #e9ecef;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.page-btn {
  padding: 8px 12px;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.page-btn.active {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.page-btn:disabled {
  background-color: #f5f5f5;
  color: #d9d9d9;
  cursor: not-allowed;
}
</style> 